# -*- coding: utf-8 -*-
"""
数据备份对话框
"""

import os
import shutil
from PyQt5.QtWidgets import (QDialog, QVBoxLayout, QHBoxLayout, QLabel, 
                            QPushButton, QMessageBox, QFileDialog, QLineEdit, QWidget)
from PyQt5.QtCore import Qt
from config import DB_PATH, BACKUP_DIR
from utils import ensure_dir, get_timestamp

class BackupDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setWindowTitle("💾 数据备份")
        self.setModal(True)
        self.resize(500, 300)
        
        # 设置对话框样式
        self.setStyleSheet("""
            QDialog {
                background-color: #f8f9fa;
                font-family: "Microsoft YaHei";
            }
            QLabel {
                color: #495057;
                font-size: 14px;
            }
            QLineEdit {
                border: 2px solid #e9ecef;
                border-radius: 6px;
                padding: 10px 12px;
                font-size: 14px;
                background-color: #ffffff;
            }
            QPushButton {
                background-color: #4a90e2;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 10px 20px;
                font-size: 14px;
                font-weight: 600;
            }
            QPushButton:hover {
                background-color: #357abd;
            }
            QPushButton:pressed {
                background-color: #2968aa;
            }
        """)
        
        self.init_ui()
    
    def init_ui(self):
        """初始化界面"""
        layout = QVBoxLayout(self)
        layout.setSpacing(20)
        layout.setContentsMargins(30, 30, 30, 30)
        
        # 标题
        title_label = QLabel("💾 数据库备份")
        title_label.setStyleSheet("""
            QLabel {
                font-size: 20px;
                font-weight: bold;
                color: #4a90e2;
                margin-bottom: 10px;
                padding: 10px 0;
                border-bottom: 2px solid #4a90e2;
            }
        """)
        layout.addWidget(title_label)
        
        # 备份说明
        info_frame = QWidget()
        info_frame.setStyleSheet("""
            QWidget {
                background-color: #e3f2fd;
                border: 1px solid #4a90e2;
                border-radius: 8px;
                padding: 15px;
            }
        """)
        info_layout = QVBoxLayout(info_frame)
        
        info_label = QLabel("📋 备份当前数据库到指定位置")
        info_label.setStyleSheet("font-weight: 600; color: #1976d2; font-size: 15px;")
        info_layout.addWidget(info_label)
        
        # 当前数据库路径
        current_db_label = QLabel(f"📍 当前数据库路径：{DB_PATH}")
        current_db_label.setWordWrap(True)
        current_db_label.setStyleSheet("color: #495057; font-size: 13px; margin-top: 5px;")
        info_layout.addWidget(current_db_label)
        
        layout.addWidget(info_frame)
        
        # 备份路径选择
        path_frame = QWidget()
        path_frame.setStyleSheet("""
            QWidget {
                background-color: #ffffff;
                border: 1px solid #e9ecef;
                border-radius: 8px;
                padding: 15px;
            }
        """)
        path_layout = QVBoxLayout(path_frame)
        path_layout.setSpacing(10)
        
        path_label = QLabel("🎯 备份路径：")
        path_label.setStyleSheet("font-weight: 600; color: #495057; font-size: 14px;")
        path_layout.addWidget(path_label)
        
        input_layout = QHBoxLayout()
        input_layout.setSpacing(10)
        
        self.backup_path_input = QLineEdit()
        self.backup_path_input.setText(os.path.join(BACKUP_DIR, f"backup_{get_timestamp()}.db"))
        self.backup_path_input.setReadOnly(True)
        self.backup_path_input.setStyleSheet("""
            QLineEdit {
                background-color: #f8f9fa;
                border: 2px solid #e9ecef;
                border-radius: 6px;
                padding: 10px 12px;
                font-size: 14px;
            }
        """)
        
        browse_button = QPushButton("📁 浏览...")
        browse_button.clicked.connect(self.browse_backup_path)
        browse_button.setStyleSheet("""
            QPushButton {
                background-color: #17a2b8;
                color: white;
                border: none;
                border-radius: 6px;
                padding: 10px 20px;
                font-size: 14px;
                font-weight: 600;
            }
            QPushButton:hover {
                background-color: #138496;
            }
            QPushButton:pressed {
                background-color: #117a8b;
            }
        """)
        
        input_layout.addWidget(self.backup_path_input)
        input_layout.addWidget(browse_button)
        path_layout.addLayout(input_layout)
        
        layout.addWidget(path_frame)
        
        # 备份按钮
        backup_button = QPushButton("🚀 开始备份")
        backup_button.clicked.connect(self.perform_backup)
        backup_button.setStyleSheet("""
            QPushButton {
                background-color: #28a745;
                color: white;
                border: none;
                border-radius: 8px;
                padding: 15px;
                font-size: 16px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #218838;
            }
            QPushButton:pressed {
                background-color: #1e7e34;
            }
        """)
        layout.addWidget(backup_button)
        
        layout.addStretch()
    
    def browse_backup_path(self):
        """浏览备份路径"""
        default_dir = BACKUP_DIR
        ensure_dir(default_dir)
        
        file_path, _ = QFileDialog.getSaveFileName(
            self, "选择备份文件位置", 
            os.path.join(default_dir, f"backup_{get_timestamp()}.db"),
            "数据库文件 (*.db)"
        )
        
        if file_path:
            self.backup_path_input.setText(file_path)
    
    def perform_backup(self):
        """执行备份"""
        backup_path = self.backup_path_input.text()
        
        if not backup_path:
            QMessageBox.warning(self, "警告", "请选择备份路径")
            return
        
        try:
            # 确保备份目录存在
            backup_dir = os.path.dirname(backup_path)
            ensure_dir(backup_dir)
            
            # 复制数据库文件
            shutil.copy2(DB_PATH, backup_path)
            
            # 获取备份文件大小
            file_size = os.path.getsize(backup_path)
            size_mb = file_size / (1024 * 1024)
            
            QMessageBox.information(
                self, "备份成功", 
                f"数据库已成功备份到：\n{backup_path}\n\n"
                f"文件大小：{size_mb:.2f} MB"
            )
            
            self.accept()
            
        except Exception as e:
            QMessageBox.critical(self, "备份失败", f"备份过程中出现错误：\n{str(e)}")